package com.tang.Date20240611;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author tmh
 * @date 2024/6/12 22:26
 * @description
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        // 创建线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 20,
                0, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1024));
        final int taskCount = 5;    // 任务总数
        // 单次计数器
        CountDownLatch countDownLatch = new CountDownLatch(taskCount); // ①
        // 添加任务
        for (int i = 0; i < taskCount; i++) {
            final int finalI = i;
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 随机休眠 0-4s
                        int sleepTime = new Random().nextInt(5);
                        TimeUnit.SECONDS.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(String.format("任务%d执行完成", finalI));
                    // 线程执行完，计数器 -1
                    countDownLatch.countDown();  // ②
                }
            });
        }
        // 阻塞等待线程池任务执行完
        countDownLatch.await();  // ③
        // 线程池执行完
        System.out.println();
        System.out.println("线程池任务执行完成！");
    }

}
